package com.example.springstudy.controller;

import com.example.springstudy.base.Result;
import com.example.springstudy.base.annotation.DataScope;
import com.example.springstudy.base.annotation.SaveLog;
import com.example.springstudy.dao.dto.EmployeeDto;
import com.example.springstudy.dao.res.EmployeeListRes;
import com.example.springstudy.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @DataScope
    @GetMapping("/list")
    public Result<EmployeeListRes> getEmployee(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "100") Integer size) {
        return Result.success(employeeService.getAllEmployees(page, size));
    }

    @SaveLog("更新员工")
    @PostMapping("/addOrUpdate")
    public Result<Boolean> addOrUpdate(@RequestBody EmployeeDto employeeDto) {
        try{
            Assert.hasText(employeeDto.getEmployeeName(), "员工姓名不能为空！");
            Assert.isTrue(employeeDto.getDeptId()!=0, "部门不能为空！");
            Assert.isTrue(employeeDto.getJobId()!=0, "职位不能为空！");
            if(employeeDto.getId()==null || employeeDto.getId()==0){
                return Result.success(employeeService.saveEmployee(employeeDto));
            } else {
                return Result.success(employeeService.updateEmployee(employeeDto));
            }
        } catch (Exception e){
            return Result.failed(e.getMessage());
        }

    }
}
